<template>
  <div :class="ns.b()">
    <div :class="ns.e('header')"></div>
    <div :class="ns.e('body')" ref="canvas"></div>
    <div :class="ns.e('footer')"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useNamespace } from '@mdfe/medi-ui';
import { init } from 'echarts';
import bIZuJianWH from '@/api/juecefxpt/bIZuJianWH';
import { transModelToLineData } from '@/views/zuJianSJ/components/widgetType/line.js';
import elementResizeDetectorMaker from 'element-resize-detector';

defineOptions({
  name: 'mic-line-block',
});

const props = defineProps({
  widgetStyle: Object,
  isComp: {
    type: Boolean,
    default: false,
  },
  widget: Object,
});

const emit = defineEmits(['set', 'EchartClick']);

const ns = useNamespace('bi-line-block');

let instance = null;
const canvas = ref();

const style = ref();
const seriesOption = ref();

const erd = elementResizeDetectorMaker();

let resizeListener = null;

async function search(id, data) {
  data.zuJianTBLX = 1;
  try {
    const res = await bIZuJianWH.generateDataList({
      gongChengSJJID: id,
      zuJianNR: JSON.stringify(data),
    }); //注意空格，导致报错
    if (res.data) {
      const index = res.fieldList.findIndex((item) => {
        return item.ziDuanMC === data.xuanZhongZBList?.[0]?.ziDuanMC;
      });
      const obj = {
        series: [],
        xAxis: [],
        legend: { data: [] },
      };
      res.fieldList.forEach((item, i) => {
        if (i < index || index == -1) {
          obj.xAxis.push({
            name: item.ziDuanMC,
            type: 'category',
            // prettier-ignore
            data: res.data[i],
          });
        } else {
          obj.series.push({
            type: 'line',
            name: item.ziDuanMC,
            data: res.data[i],
          });
          obj.legend.data.push(item.ziDuanMC);
        }
      });
      instance.setOption(obj);
    }
  } catch (e) {
    console.error(e);
  }
}
function setOption(options) {
  if (!options) return;
  style.value = options;
  const { series } = instance.getOption();
  const obj = transModelToLineData(options);
  seriesOption.value = Object.assign({}, seriesOption.value, obj.series);
  const newSeries = series.map((item) => {
    return Object.assign({}, item, seriesOption.value);
  });
  obj.series = newSeries;
  instance.setOption(obj);
}

onMounted(() => {
  nextTick(() => {
    instance = init(canvas.value);

    // 指定图表的配置项和数据

    style.value = props.widgetStyle || {};
    seriesOption.value = {};
    instance.setOption({
      xAxis: {
        type: 'category',
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          type: 'bar',
        },
      ],
    });
    emit('set', true);

    if (props.isComp && props.widget) {
      search(props.widget.gongChengSJJID, props.widget);
      setOption(props.widget.styleConfig);
      instance.on('click', (params) => {
        const { xAxis } = instance.getOption();
        const list = props.widget.xuanZhongWDList.map((item, index) => {
          return {
            ziDuanMC: item.ziDuanMC,
            ziDuanMS: item.ziDuanMS,
            shuJuLXDM: item.shuJuLXDM,
            value: xAxis[index].data[params.dataIndex],
          };
        });
        const index = props.widget.xuanZhongZBList.findIndex(
          (item) => item.ziDuanMC === params.seriesName,
        );
        list.push({
          ziDuanMC: params.seriesName,
          ziDuanMS: props.widget.xuanZhongZBList[index].ziDuanMS,
          shuJuLXDM: props.widget.xuanZhongZBList[index].shuJuLXDM,
          value: params.value,
        });
        emit('EchartClick', { event: list, widget: props.widget });
      });
    }

    resizeListener = erd.listenTo(canvas.value, () => {
      instance.resize();
    });
  });
});

onBeforeUnmount(() => {
  if (resizeListener) {
    erd.uninstall(canvas.value);
  }
  instance.off('click');
});

defineExpose({
  search,
  setOption,
  widget: props.widget,
});
</script>

<style lang="scss" scoped>
@include c('bi-line-block') {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  @include e('header') {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: var(--md-spacing-2);
  }
  @include e('label') {
    color: #222;
    font-size: var(--md-font-3);
  }
  @include e('body') {
    flex: 1;
  }
}
</style>
